package com.google.code.mamule.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * Created with IntelliJ IDEA. User: borck_000 ; Date: 12/23/13 ; Time: 2:39 PM
 */
@Configuration
@EnableWebSecurity// (debug = true)
public class MamuleSecurity extends WebSecurityConfigurerAdapter {

  public static final GrantedAuthority ROLE_USER = new SimpleGrantedAuthority("USER");
  public static final GrantedAuthority ROLE_ADMIN = new SimpleGrantedAuthority("ADMIN");

  @Autowired
  private UserDetailsService userDetails;

  public MamuleSecurity() {
    super(true); // disables all default settings
  }

  // disable security on register URL
  @Override
  public void configure(final WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/mamule/user/register");
  }

  @Override
  protected void configure(final HttpSecurity http) throws Exception {
    http
        // setup chain
        .exceptionHandling()
        .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
            // do actual configuration
        .httpBasic()
        .realmName("mamule-realm")
        .and()
        .authorizeRequests()
        .antMatchers(HttpMethod.POST, "/mamule/price**").hasAuthority(ROLE_ADMIN.getAuthority())
        .anyRequest().authenticated()
    ;
  }

  @Override
  public void configure(final AuthenticationManagerBuilder auth) throws Exception {
    auth
        .userDetailsService(userDetails)
    ;
  }
}
